import { ResponseInterceptor } from './../../../interceptor/response/response.interceptor';
import { GoodResponse } from './../../../util/response';
import { GoodsColorService } from './../../../service/goods-color/goods-color.service';
import { GoodsService } from './../../../service/goods/goods.service';
import { Controller, Post, BadRequestException, Req, Res, Get, UseInterceptors, Body, Patch, Delete, Query } from '@nestjs/common';
import { CookieService } from 'src/service/cookie/cookie.service';
import config from 'src/config/config';
import * as lodash from 'lodash';

@Controller(`${config.shopApiPath}/cart`)
@UseInterceptors(ResponseInterceptor)
export class CartController {
    constructor(
        private readonly goodsService: GoodsService,
        private readonly goodsColorService: GoodsColorService,
        private readonly cookieService: CookieService,
    ) {}
    @Get()
    getCart(@Req() req) {
        // console.log(req.ip);
        // ::ffff:10.71.189.72
        return this.cookieService.get(req, config.cartKey) || [];
    }
    @Get('cartItem')
    getCartItem(@Query() query, @Req() req) {
        const { _id, color } = query;
        const cartList = this.cookieService.get(req, config.cartKey) || [];
        return cartList.find((item) => item._id === _id && item.color === color) || {};
    }
    @Post()
    async addToCart(@Req() req, @Res() res, @Body() body) {
        const { goods_id, color_id } = body;
        if (!goods_id || !color_id) throw new BadRequestException('请传必传参数:goods_id、color_id');
        const goodsResult = await this.goodsService.getModel().find({ _id: goods_id });
        const colorResult = await this.goodsColorService.find({ _id: color_id });
        if (!goodsResult.length || !colorResult.length) throw new BadRequestException('商品或所选颜色不存在');
        const unwindGoods = goodsResult[0];
        const unwindColor = colorResult[0];
        const giftResult = await this.goodsService.getModel().find({ _id: { $in: unwindGoods.goods_gift } });
        const currentData = {
            _id: goods_id,
            title: unwindGoods.title,
            price: unwindGoods.shop_price,
            goods_version: unwindGoods.goods_version,
            num: 1,
            color: unwindColor.color_name,
            goods_img: unwindGoods.goods_img,
            goods_gift: giftResult,
            goods_attr: '',
            checked: true,
        };
        const cartResult = this.cookieService.get(req, config.cartKey);
        if (!cartResult) {
            this.cookieService.set(res, config.cartKey, [currentData]);
        } else {
            const sameCartIndex = lodash.findIndex(
                cartResult,
                (item: any) => item._id === goods_id && item.color === unwindColor.color_name,
            );
            if (sameCartIndex !== -1) {
                currentData.num = cartResult[sameCartIndex].num + 1;
                cartResult[sameCartIndex] = currentData;
                this.cookieService.set(res, config.cartKey, cartResult);
            } else {
                this.cookieService.set(res, config.cartKey, [...cartResult, currentData]);
            }
        }
        res.send(GoodResponse(null, '添加成功'));
    }
    @Patch('changNum')
    changeNum(@Body() body, @Req() req, @Res() res) {
        const { num = 1, _id, color } = body;
        if (!_id || !color) throw new BadRequestException('请传必传参数:_id、color');
        const currentRecord = this.cookieService.get(req, config.cartKey);
        if (!currentRecord?.length) throw new BadRequestException('当前购物车为空');
        const currentIndex = lodash.findIndex(currentRecord, (item: any) => item._id === _id && item.color === color);
        if (currentIndex === -1) throw new BadRequestException('该商品不存在');
        if (num === 1) {
            currentRecord[currentIndex].num++;
        }
        if (num === -1) {
            currentRecord[currentIndex].num--;
            if (currentRecord[currentIndex].num <= 0) {
                currentRecord.splice(currentIndex, 1);
            }
        }
        this.cookieService.set(res, config.cartKey, currentRecord);
        res.send(GoodResponse(null, '修改成功'));
    }
    @Patch('changeChecked')
    changeChecked(@Body() body, @Req() req, @Res() res) {
        const { cartList } = body;
        let cartResult = this.cookieService.get(req, config.cartKey);
        if (!cartResult?.length) throw new BadRequestException('购物车为空');
        const canEdit = cartList.every((item) => item._id && item.color);
        if (!canEdit) throw new BadRequestException('参数不合法');
        cartResult = cartResult.map((item) => ({ ...item, checked: false }));
        cartList.forEach((item) => {
            const findIndex = lodash.findIndex(cartResult, (item1: any) => item1._id === item._id && item1.color === item.color);
            if (findIndex !== -1) {
                cartResult[findIndex].checked = true;
            }
        });
        this.cookieService.set(res, config.cartKey, cartResult);
        res.send(GoodResponse(null, '修改成功'));
    }
    @Delete()
    deleteRecords(@Body() body, @Req() req, @Res() res) {
        const { ids = [], _id } = body;
        const cartResult = this.cookieService.get(req, config.cartKey);
        if (!cartResult?.length) throw new BadRequestException('购物车为空');
        ids.forEach((_id) => {
            const droppedIndex = lodash.findIndex(cartResult, (record: any) => record._id === _id);
            if (droppedIndex !== -1) {
                cartResult.splice(droppedIndex, 1);
            }
        });
        if (_id) {
            const droppedIndex = lodash.findIndex(cartResult, (record: any) => record._id === _id);
            if (droppedIndex !== -1) {
                cartResult.splice(droppedIndex, 1);
            }
        }
        this.cookieService.set(res, config.cartKey, cartResult);
        res.send(GoodResponse(null, '删除成功'));
    }
}
